/**
 * 
 */
package org.xtense.engine.actions;

import java.util.HashMap;

import org.xtense.data.DBManager;
import org.xtense.exception.XtenseException;
import org.xtense.log.iLog;
import org.xtense.model.actions.ResultCache;
import org.xtense.model.actions.UpdateCache;

/**
 * @author saber
 *
 */
public class UpdateAction extends XAction {
	private UpdateCache cache = new UpdateCache();
	private static HashMap<Integer, UpdateAction> instances = new HashMap<Integer, UpdateAction>();

	protected UpdateAction(DBManager manager, String documentName) {
		super(manager, documentName);
		documentID = super.getDocumentIDfromName(manager, documentName);
		if (documentID < 0) {
			try {
				throw new XtenseException(XtenseException.NoSuchDoc);
			} catch (XtenseException e) {
				iLog.warn(e);
			}
		}
		instances.put(documentID, this);
	}

	protected UpdateAction(DBManager manager, int documentID) {
		super(manager, documentID);
		instances.put(documentID, this);
	}
	
	public static UpdateAction getInstance(int documentID) {
		
		return instances.get(documentID);
	}
	
	// wrong.....if use a different database config
	public static UpdateAction getInstance(DBManager database,
			String documentName) {
		return instances.get(getDocumentIDfromName(database, documentName));
	}
	
	public UpdateCache getCache() {
		return cache;
	}
	
	public void updatePre(int elementPre, int size, boolean isAdd) {
		if (isAdd) {
			cache.updateForAdd(elementPre, size);
			ResultCache.updateForAdd(documentID, elementPre, size);
		} else {
			cache.updateForDel(elementPre, size);
			ResultCache.updateForDel(documentID, elementPre, size);
		}
	}

	/* (non-Javadoc)
	 * @see org.extense.engine.actions.XAction#execute(java.lang.Object)
	 */
	@Override
	public Object execute(Object object) {
		for (String s : cache.getSql()) {
			System.out.println(s);
			database.executeSqlUpdate(s);
			
		}
		cache.getSql().clear();
		return null;
	}
	
	protected void finalize() throws Throwable {
		ResultCache.clean(documentID);
		super.finalize();
	}

}
